import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      // 修改全局请求头，满足后端oAuth2认证
      config.headers['authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000) {
      // 50008: Illegal token; 50010: invalid token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50010 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('您已经登出，您可以取消以停留在此页面，或再次登录', '确认注销', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      else {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err：' + error) // for debug
    let msg = error.message
    // 当响应异常时做一些处理
    if (error && error.response) {
      switch (error.response.status) {
        // 其他错误，直接抛出错误提示
        case 400:
          msg = '请求错误(400)';
          break;
        case 401:
          msg = '未授权，请重新登录(401)';
          break;
        case 403:
          msg = '拒绝访问(403)';
          break;
        case 404:
          msg = '请求出错(404)';
          break;
        case 408:
          msg = '请求超时(408)';
          break;
        case 500:
          msg = '服务器错误(500)';
          break;
        case 501:
          msg = '服务未实现(501)';
          break;
        case 502:
          msg = '网络错误(502)';
          break;
        case 503:
          msg = '服务不可用(503)';
          break;
        case 504:
          msg = '网络超时(504)';
          break;
        case 505:
          msg = 'HTTP版本不受支持(505)';
          break;
        default:
          msg = `连接出错(${error.response.status})!`;
      }
    } else {
      msg = '连接服务器失败！'
    }
    Message({
      message: msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
